package com.hongdee.insurance.commission.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.commission.dao.ITCommissionDao;
import com.hongdee.insurance.commission.entity.TInsuranceCommission;
import com.hongdee.insurance.commission.service.ITCommissionNewService;
import com.hongdee.insurance.commission.service.ITCommissionSrevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 佣金更新后模板
 */
@Service
public class TCommissionNewServiceImpl implements ITCommissionNewService {


    @Autowired
    private ITCommissionDao itCommissionDao;
    @Autowired
    private ITCommissionSrevice commissionSrevice;


    /**
     * 1、先根据提交的内容生成佣金费率实体
     * 2、检测每一个佣金费率实体是否有时间重叠
     * 3、如无重叠 并且未抛出异常则进行添加
     * @param data
     * @param carCompanyList
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveInsuranceCommission(Map<String,Object> data,List<String> carCompanyList,String uid) throws Exception {
        List<TInsuranceCommission> commissionList=new ArrayList<>();
        //判定是单商业 还是单交强 还是交商共保
        //获得佣金实体 有多少个应用单位 就生成多少个佣金实体
        String iscompulsoryinsurance=StringUtil.formatEmpty(data.get("iscompulsoryinsurance"));
        if(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()).equals(iscompulsoryinsurance)){ // 单交强
            if(!"".equals(StringUtil.formatEmpty(data.get("jqCommission")))) {
                this.getInsurnaceCommission(data, StringUtil.formatEmpty(data.get("jqCommission")), "0",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }

            if(!"".equals(StringUtil.formatEmpty(data.get("ccsCommission")))) {
                this.getInsurnaceCommission(data, StringUtil.formatEmpty(data.get("ccsCommission")), "2",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }
        }
        if(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()).equals(iscompulsoryinsurance)){ // 单商业
            if(!"".equals(StringUtil.formatEmpty(data.get("syCommission")))) {
                this.getInsurnaceCommission(data, StringUtil.formatEmpty(data.get("syCommission")), "1",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }
        }
        if(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()).equals(iscompulsoryinsurance)){ // 交商共保
            if(!"".equals(StringUtil.formatEmpty(data.get("jqCommission")))) {
                this.getInsurnaceCommission(data,StringUtil.formatEmpty(data.get("jqCommission")), "0",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }
            if(!"".equals(StringUtil.formatEmpty(data.get("syCommission")))) {
                this.getInsurnaceCommission(data, StringUtil.formatEmpty(data.get("syCommission")), "1",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }

            if(!"".equals(StringUtil.formatEmpty(data.get("ccsCommission")))) {
                this.getInsurnaceCommission(data, StringUtil.formatEmpty(data.get("ccsCommission")), "2",
                        StringUtil.formatEmpty(data.get("startDate")), StringUtil.formatEmpty(data.get("stopDate")), uid,
                        carCompanyList, commissionList);
            }
        }
        if(commissionList.size()>0) {
            hisDateCompare(commissionList);
            this.itCommissionDao.saveOrUpdateList(commissionList);
        }else{
            throw new Exception("交强险、商业险至少提供一项佣金费率!!");
        }
    }

    /**
     * 生成佣金 实体类
     * @param data
     * @param commission
     * @param insuranceType
     * @param startDate
     * @param stopDate
     * @param uid
     * @param carCompanyList
     * @param commissionList
     */
    private void getInsurnaceCommission(Map<String,Object> data,String commission,String insuranceType,
            String startDate,String stopDate,String uid,List<String> carCompanyList,List<TInsuranceCommission> commissionList) throws Exception {
        for (String key:carCompanyList) {
            TInsuranceCommission insuranceCommission=new TInsuranceCommission();
            insuranceCommission.setStatus("1");
            insuranceCommission.setCommission(commission);
            insuranceCommission.setInsuranceType(insuranceType);
            insuranceCommission.setInsureType(StringUtil.formatEmpty(data.get("insureType")));
            insuranceCommission.setCommissionType(StringUtil.formatEmpty(data.get("commissionType")));
            insuranceCommission.setStartDate(startDate);
            insuranceCommission.setStopDate(stopDate);
            insuranceCommission.setCompanyId(StringUtil.formatEmpty(data.get("companyId")));
            insuranceCommission.setCreateCompanyId(TokenUtil.getCompanyId(uid));
            insuranceCommission.setIscompulsoryinsurance(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")));
            insuranceCommission.setArea(StringUtil.formatEmpty(data.get("area")));
            String[] keys = key.split("_");
            String applyUnit = keys[0];
            String companyName = keys[1];
            insuranceCommission.setCreateTime(DateUtils.getNowTime());
            insuranceCommission.setApplyUnitName(companyName);
            insuranceCommission.setApplyUnit(applyUnit);
            insuranceCommission.setRemark(StringUtil.formatEmpty(data.get("remark")));
            commissionList.add(insuranceCommission);
        }
    }

    /**
     * 检测每一个实体是否有时间重叠
     * @param tInsuranceCommissions
     * @throws Exception
     */
    @Override
    public void hisDateCompare(List<TInsuranceCommission> tInsuranceCommissions) throws Exception {
        for (TInsuranceCommission entity:tInsuranceCommissions) {
            if("".equals(entity.getCompanyId())){
                throw new Exception("未选择保险公司!!");
            }
            StringBuffer sqlBuf = new StringBuffer();
            sqlBuf.append(" select * from t_insurance_commission where insurance_type = ? and insure_type=? and commission_type = ? and company_id =? " +
                    " and apply_unit=? and area=? and status='1' ");
            List params = new ArrayList();
            params.add(entity.getInsuranceType());
            params.add(entity.getInsureType());
            params.add(entity.getCommissionType());
            params.add(entity.getCompanyId());
            params.add(entity.getApplyUnit());
            params.add(entity.getArea());
            //增加是否单交强
            if(!"".equals(StringUtil.formatEmpty(entity.getIscompulsoryinsurance()))){
                sqlBuf.append(" and iscompulsoryinsurance=? ");
                params.add(entity.getIscompulsoryinsurance());
            }
            if(!"".equals(StringUtil.formatEmpty(entity.getId()))){
                sqlBuf.append(" and id<>? ");
                params.add(entity.getId());
            }

            sqlBuf.append(" order by stop_date desc ");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar date = Calendar.getInstance();
            date.setTime(sdf.parse(entity.getStartDate()));
            date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
            String insuranceType="0".equals(StringUtil.formatEmpty(entity.getInsuranceType()))?"交强险":"商业险";
            //常规佣金
            if (entity.getCommissionType() != null && entity.getCommissionType().toString().equals("0")) {
                List<Map<String, Object>> data = this.itCommissionDao.list(sqlBuf.toString(), params.toArray());
                if (data.size() != 0) {
                    commissionSrevice.checkCommissionDate(data,"应用单位["+entity.getApplyUnitName()+"]["+insuranceType+"]常规佣金起止时间重叠!!",entity);
                }
            }
            //促销佣金
            if (entity.getCommissionType() != null && entity.getCommissionType().toString().equals("1")) {
                List<Map<String, Object>> data = this.itCommissionDao.list(sqlBuf.toString(), params.toArray());
                if (data.size() != 0) {
                    commissionSrevice.checkCommissionDate(data,"应用单位["+entity.getApplyUnitName()+"]["+insuranceType+"]促销佣金起止时间重叠!!",entity);
                }
            }
        }
    }


    //-------------------------------------------------分页-------------------------------------------------------------

    /**
     * 分页查询
     * @param uid
     * @param start
     * @param limit
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from ( ");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_code," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,t.apply_unit_name as oName,t.remark,t.status,t.area," +
                " area.label disp,case when t.iscompulsoryinsurance='0' then '单交强' when t.iscompulsoryinsurance='1' then '单商业'" +
                " when t.iscompulsoryinsurance ='2' then '交商共保' end iscompulsoryinsurance" +
                " from t_insurance_commission t "+
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +

                " where t.apply_unit<>'0' ");
        List params = new ArrayList();
        if(!"0".equals(TokenUtil.getCompanyId(uid))){
            sql.append(" and t.create_company_id=? ");
            params.add(TokenUtil.getCompanyId(uid));
        }else{
            List<Map<String,Object>> list=TokenUtil.getDataCompany(uid);
            sql.append("  and t.create_company_id in( ");
            for (int i = 0; i < list.size(); i++) {
                String id= StringUtil.formatEmpty(list.get(i).get("id"));
                sql.append("?,");
                params.add(id);
            }
            sql.append("?");
            params.add(TokenUtil.getCompanyId(uid));
            sql.append(" ) ");
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("applyUnitId")))){
            sql.append(" and t.apply_unit=? ");
            params.add(StringUtil.formatEmpty(data.get("applyUnitId")));
        }
        commissionSrevice.queryCommissionPageToSql(sql,data,params);
        sql.append(" union all ");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_code," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,t.apply_unit_name as oName,t.remark,t.status,t.area," +
                " area.label disp ,case when t.iscompulsoryinsurance='0' then '单交强' when t.iscompulsoryinsurance='1' then '单商业'" +
                " when t.iscompulsoryinsurance ='2' then '交商共保' end iscompulsoryinsurance" +
                " from t_insurance_commission t " +
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +

                " where t.apply_unit='0' ");
        commissionSrevice.queryCommissionPageToSql(sql,data,params);
        sql.append(" ) temp  ");
        sql.append(" ORDER BY temp.company_id DESC,temp.start_date ASC,temp.insurance_type desc,temp.insure_type desc ");
        return this.itCommissionDao.page(sql.toString(), params.toArray(), start, limit);
    }
    //-----------------------------------------------更新佣金接口--------------------------------------------------------

    /**
     * 更新佣金
     * @param insuranceCommission
     * @param uid
     * @throws Exception
     */
    @Override
    public void updateInsuranceCommission(TInsuranceCommission insuranceCommission,String uid) throws Exception {
        insuranceCommission.setUpdateUser(uid);
        insuranceCommission.setUpdateTime(DateUtils.getNowTime());
        List<TInsuranceCommission> list=new ArrayList<>();
        list.add(insuranceCommission);
        hisDateCompare(list);
        this.itCommissionDao.saveOrUpdate(insuranceCommission);
        commissionSrevice.updOrderItemCommissionPrice(insuranceCommission.getId(),TokenUtil.getCompanyId(uid));
    }

}
